package com.cn.appcore.adapter

import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentActivity
import androidx.viewpager2.adapter.FragmentStateAdapter

/**
 * 项目：JingShortVideo
 * 包名：com.cn.jingshortvideo.ui.main.adapter
 * 类名：CustomFragmentStateAdapter
 * 创建时间：2022/9/2 14:46
 * 创建人 @author： xiaolin
 * 描述 ：Todo...
 */
class CustomFragmentStateAdapter<F : Fragment> : FragmentStateAdapter {
    constructor(fragment: Fragment) : super(fragment)
    constructor(fragmentActivity: FragmentActivity) : super(fragmentActivity)

    val fragmentList: MutableList<F> by lazy { arrayListOf() }

    override fun getItemCount() = fragmentList.size

    override fun createFragment(position: Int) = fragmentList[position]

    fun setNewData(fragments: MutableList<F>) {
        fragmentList.clear()
        fragmentList.addAll(fragments)
        notifyDataSetChanged()
    }

    fun addData(fragment: F, position: Int = -1) {
        if (fragmentList.contains(fragment)) {
            return
        }
        if (position == -1) {
            fragmentList.add(fragment)
            notifyItemInserted(itemCount)
            notifyItemChanged(itemCount)
            return
        }
        fragmentList.add(position, fragment)
        notifyItemInserted(position)
        notifyItemChanged(position)
    }

    fun addDataList(fragments: MutableList<F>){
        val startIndex=fragmentList.size
        fragmentList.addAll(fragments)
        notifyItemRangeInserted(startIndex,fragments.size)
    }

}